<template>
  <div id="app"></div>
</template>

<script>
import mapboxgl from 'mapbox-gl';
import 'mapbox-gl/dist/mapbox-gl.css';
import MapboxLanguage from '@mapbox/mapbox-gl-language';
import { getHistoryData } from './api/historyData';

import { RulerControl, ZoomControl } from 'mapbox-gl-controls';
import 'mapbox-gl-controls/lib/controls.css';

const COLOR_LEVEL = [
  'rgba(0,255,0,0.7)',
  'rgba(255,255,255,0.7)',
  'rgba(255,125,0,0.7)',
  'rgba(255,0,0,0.7)',
  'rgba(152,0,75,0.7)',
  'rgba(178,24,43,0.7)',
];
export default {
  data() {
    return {
      // 历史数据
      historyData: null,
      // map 地图对象实例
      map: null,
    };
  },
  async created() {
    // 请求获取关于点的一些数据
    console.log('开始获取数据');
    console.time('fetchData');
    const result = await getHistoryData();
    console.log(result);

    // 将点压缩到一半
    result.features = result.features.filter((item, index) => {
      if (index % 2 === 0) return item;
    });

    this.historyData = Object.freeze(result);
    console.timeEnd('fetchData');

    this.map.on('load', () => {
      console.log('this.historyData :>> ', this.historyData);
      this.map.addSource('historyDataId', {
        type: 'geojson',
        data: this.historyData,
      });

      this.map.addLayer({
        id: 'historyPoints',
        type: 'circle',
        source: 'historyDataId',
        minzoom: 7,
        paint: {
          // Size circle radius by earthquake magnitude and zoom level  大小圈半径由 PM2.5 和缩放级别共同决定
          'circle-radius': [
            'interpolate',
            ['linear'],
            ['zoom'],
            9,
            ['interpolate', ['linear'], ['get', 'PM2.5'], 500, 1],
            10,
            // ['interpolate', ['linear'], ['get', 'mag'], 1, 5, 6, 50],
            ['interpolate', ['linear'], ['get', 'PM2.5'], 500, 0.5],
            18,
            12,
          ],
          // Color circle by earthquake magnitude  用颜色标出 PM2.5 的污染程度
          'circle-color': [
            'interpolate',
            ['linear'],
            ['get', 'PM2.5'],
            50,
            COLOR_LEVEL[0],
            100,
            COLOR_LEVEL[1],
            150,
            COLOR_LEVEL[2],
            200,
            COLOR_LEVEL[3],
            300,
            COLOR_LEVEL[4],
            500,
            COLOR_LEVEL[5],
          ],
          'circle-stroke-color': 'transparent',
          'circle-stroke-width': 0, // 圆点的边框大小
          // Transition from heatmap to circle layer by zoom level  通过缩放级别从热图过渡到圆圈层
          'circle-opacity': [
            'interpolate',
            ['linear'],
            ['zoom'],
            // zoom 比9小隐藏
            9,
            0,
            // 否则显示
            10,
            1,
          ],
        },
      });
    });
  },
  mounted() {
    mapboxgl.accessToken =
      'pk.eyJ1IjoiaW54bG54IiwiYSI6ImNsMzRmZDE4dTBhOWczaWs3a2psanphMnUifQ.iKIlYhNlW_13OqBJLOc9sw';

    const map = new mapboxgl.Map({
      container: 'app',
      //自己绘制的样式地图令牌
      antialias: true, //抗锯齿
      style: 'mapbox://styles/mapbox/dark-v10',
      center: [113.97923191113188, 22.589860256941634],
      zoom: 12,
    });

    // 汉化插件只能被调用一次
    if (mapboxgl.getRTLTextPluginStatus() === 'unavailable') {
      mapboxgl.setRTLTextPlugin(
        'https://api.mapbox.com/mapbox-gl-js/plugins/mapbox-gl-rtl-text/v0.2.3/mapbox-gl-rtl-text.js',
        () => {}, // 发生错误时的回调函数
        true // Lazy load the plugin only when text is in arabic
      );
      // 设置为中文语言，热更新情况下失效
      const language = new MapboxLanguage({
        defaultLanguage: 'zh-Hans',
      });
      map.addControl(language);
    }

    this.map = map;

    // 启用右上角的控制按钮，放大，缩小，校正方向
    map.addControl(new mapboxgl.NavigationControl());
    // 测量标尺控制器 ======================================
    map.addControl(
      new RulerControl({
        units: 'kilometers',
        labelFormat: (n) => `${n.toFixed(2)} km`,
      }),
      'top-right'
    );
    map.on('ruler.on', () => console.log('ruler: on'));
    map.on('ruler.off', () => console.log('ruler: off'));
    // ====================================================

    map.addControl(new ZoomControl(), 'top-left');

    // zoom变化时打印zoom值
    map.on('zoom', function (e) {
      console.log(e.target.getZoom());
    });
  },
  beforeDestroy() {
    this.map.removeLayer('historyPoints');
  },
};
</script>

<style>
body {
  padding: 0;
  margin: 0;
  overflow: hidden;
}
#app {
  position: absolute;
  width: 100%;
  top: 0;
  bottom: 0;
}

/* 将底部的logo和信息声明隐藏 */
.mapboxgl-ctrl-logo {
  display: none !important;
}
.mapboxgl-ctrl-bottom-right {
  display: none !important;
}
</style>
